//index.js
//获取应用实例
var common = require('../../utils/common.js');
const app = getApp()
var imgbg1,imgbg2,imgbg3
var interval
Page({
  data: {
    item: app.globalData.item,
    statusBarHeight: app.globalData.statusBarHeight,
    shareimg1: '',
    shareimg2: '',
    shareimg3: '',
    over: false,
    freeId: '',
    itempic: '',
    dcode: '',
    avatar: '',
    viewPic:'',
    showmorepic: false
  },
  onLoad: function (res) {
    console.log(res)
    if (res.freeId) {
      this.setData({
        freeId: res.freeId
      });
    } else {
      this.setData({
        freeId: ''
      });
    }
    console.log(app.globalData)
    console.log(app.globalData.item)
    
  },
  onReady() {
    this.setData({
      item: app.globalData.item
    });
    // this.shareweixinquan()
    this.imgReady()
  },
  imgReady(){
    wx.showLoading({
      title: '生成中...',
      mask: true
    })
    wx.getImageInfo({
      src: this.data.item.image,
      success: function (res) {
        that.setData({
          itempic: res.path
        })
        console.log(that.data.itempic)
      },
      fail(res) {
        console.log(res)
      }
    })
    wx.getImageInfo({
      src: app.globalData.userInfo.avatar,
      success: function (res) {
        that.setData({
          avatar: res.path
        })
        console.log(that.data.avatar)
      },
      fail(res) {
        console.log(res)
      }
    })
    //二维码本地化
    const that = this
    var scene = 'ui=' + getApp().globalData.userId + '&si=' + getApp().globalData.item.skuId + '&f=t' + '&fr=' + this.data.freeId
    common.post({
      url: '/wxa/qrcode/getUnlimitQrcode', 
      data: {
        scene: scene,
        page: 'pages/index/index',
        sessionId: app.globalData.sessionId,
        width: '236',
        auto_color: 'false',
        line_color: '{"r":"255","g":"255","b":"255"}',
        is_hyaline: 'true'
      }
    })
      .then((res) => {
        console.log(res.data)
        if (res.data.code == 0) {
          console.log(res.data)
          console.log(res.data.qrcodeLink)
          wx.getImageInfo({
            src: res.data.qrcodeLink,
            success: function (res) {
              that.setData({
                dcode: res.path
              })
              console.log(that.data.dcode)
            },
            fail(res) {
              console.log(res)
            }
          })
        }
      }).catch((res) => {
        console.log(res)
        app.timeOutTip()
      })

    
    //计时器
    let promise = new Promise((resolve, reject) => {
      let timer = setInterval(() => {
        // console.log(app.globalData.sessionId,app.globalData.userId)
        if (that.data.itempic !== '' && that.data.dcode !== '' && that.data.avatar !== '') {
          clearInterval(timer);
          resolve(that.data);
          that.shareItemPic()
          
        }
      }, 250);
    });
  },
  shareItemPic(){
    // console.log(id)
    console.log('star')
    const that = this
    var format = function (value) {
      var html, _val;
      value = Number(value).toFixed(2);
      if (value == 0) {
        value = 0;
        return html = "<text>0</text>";
      } else {
        value = Number(value).toFixed(2);
      }
      _val = value.split('.');
      return html = _val[0] + '.' + _val[1];
    }
    var row1size = function (name) {
      var str = name;
      // str = str.slice(0, 36) + '...';
      length = 0.0;
      finalStr = "";
      for (i = 0; i < name.length; i++) {
        if (name[i].match("[0-9a-zA-Z]") || name[i] == " ") {
          length += 0.5;
        } else {
          length += 1;
        }

        finalStr += name[i];
        if (length > 22) {
          break;
        }
      }
      return finalStr;
    }
    var row2size = function (name) {
      var str = name;
      // str = str.slice(0, 36) + '...';
      length = 0.0;
      finalStr = "";
      for (i = 0; i < name.length; i++) {
        if (name[i].match("[0-9a-zA-Z]") || name[i] == " ") {
          length += 0.5;
        } else {
          length += 1;
        }
        if (length > 23) {
          finalStr += name[i];
        }
        if (length > 43) {
          break;
        }
      }
      return finalStr + '...';
    }
    var price1 = format(this.data.item.price)
    if (this.data.item.coupons) {
      var price2 = format(this.data.item.price - this.data.item.coupons[0].discount)
      var reduce = '优惠券:￥ ' + this.data.item.coupons[0].discount
    } else {
      var price2 = format(this.data.item.price)
      var reduce = ''
    }
    if (this.data.item.comments > 0){
      if (this.data.item.goodCommentsRate > 0){
        var txt1 = this.data.item.comments + '条评论' + ' 好评率' + this.data.item.goodCommentsRate + '%'
      }else{
        var txt1 = this.data.item.comments + '条评论'
      }
      
    }else{
      var txt1 = ''
    }
    var txt2 = '你的好友' + app.globalData.userInfo.nickname
    const sharepic = wx.createCanvasContext('myCanvas4')
    var str1 = row1size(this.data.item.title)
    var str2 = row2size(this.data.item.title)
    console.log(str1)
    console.log(str2)
    // sharepic.drawImage(imgbg, 0, 0, 1080, 1535)
    sharepic.setFillStyle('#fff')
    sharepic.fillRect(0, 0, 1080, 1535)
    sharepic.drawImage(that.data.itempic, 0, 0, 1080, 1080)
    sharepic.setFontSize(40)
    sharepic.setFillStyle('#000')
    sharepic.setTextAlign('right')
    console.log(str1)
    sharepic.fillText(str1, 1050, 1136)
    sharepic.setTextAlign('left')
    sharepic.fillText(str2, 44, 1186)
    sharepic.setFillStyle('#f95050')
    sharepic.fillRect(44, 1096, 102, 50)
    sharepic.setFontSize(32)
    sharepic.setTextAlign('left')
    sharepic.setFillStyle('white')
    sharepic.fillText('京东', 62, 1130)
    sharepic.setFontSize(34)
    sharepic.setTextAlign('left')
    sharepic.setFillStyle('#f95050')
    sharepic.fillText('券后价:￥', 44, 1248)
    sharepic.setFontSize(56)
    sharepic.fillText(price2, 210, 1257)
    sharepic.setFillStyle('#999999')
    sharepic.setFontSize(34)
    sharepic.fillText('京东价:￥', 44, 1322)
    sharepic.fillText(price1, 210, 1322)
    const metrics = sharepic.measureText(price1)
    var txtwidth = parseInt(metrics.width)
    console.log(txtwidth)
    sharepic.rect(174, 1339, txtwidth, 1)
    sharepic.setFillStyle('#f95050')
    sharepic.fillText(reduce, 350, 1322)
    sharepic.setTextAlign('right')
    if (txt1 !== ''){
      sharepic.setFillStyle('#999999')
      sharepic.fillText(txt1, 1043, 1242)
    }
    sharepic.save();
    sharepic.arc(106 / 2 + 42, 106 / 2 + 1368, 106 / 2, 0, Math.PI * 2, false);
    sharepic.clip();
    sharepic.drawImage(that.data.avatar, 42, 1368, 106, 106);
    sharepic.restore();
    // if (edata.is99) {
    //   sharepic.drawImage('/img/freeico.png', 760, 422, 243, 221)
    // }
    sharepic.drawImage(that.data.dcode, 853, 1257, 190, 190)
    sharepic.setTextAlign('left')
    sharepic.setFillStyle('#000')
    sharepic.setFontSize(32)
    sharepic.fillText(txt2, 174, 1414)
    sharepic.setFontSize(28)
    sharepic.setFillStyle('#999999')
    sharepic.fillText('推荐您享受京东内购优惠', 174, 1462)
    sharepic.fillText('长按识别', 900, 1488)
    console.log('star draw')
    console.log(sharepic)
    sharepic.draw(false, function (e) {
      console.log(e)
      wx.canvasToTempFilePath({
        x: 0,
        y: 0,
        width: 1080,
        height: 1535,
        destWidth: 1080,
        destHeight: 1535,
        canvasId: 'myCanvas4',
        success: function (res) {
          console.log(res.tempFilePath)
          that.setData({
            viewPic: res.tempFilePath,
            saveimg: res.tempFilePath
          });
          wx.hideLoading()
        },
        fail(res){
          console.log(res)
          wx.hideLoading()
        }
      })
    })
  },
  savemoreimg(){
    wx.showLoading({
      title: '生成中...',
      mask: true
    })
    const that = this
    var edata = this.data.item
    var myCanvasId1 = 'myCanvas',
      myCanvasId2 = 'myCanvas2',
      myCanvasId3 = 'myCanvas3'
    // console.log(edata)
    if (this.data.item.is99) {
      imgbg1 = '/img/picbg3.jpg'
      imgbg2 = '/img/picbg4.jpg'
      imgbg3 = '/img/picbg5.jpg'
    } else {
      imgbg1 = '/img/picbg.jpg'
      imgbg2 = '/img/picbg6.jpg'
      imgbg3 = '/img/picbg7.jpg'
    }
    var str = edata.title;
    str = str.slice(0, 30)
    var str1 = str.slice(0, 16)
    var str2 = str.slice(17, 30) + '...'
    var format = function (value) {
      var html, _val;
      value = Number(value).toFixed(2);
      if (value == 0) {
        value = 0;
        return html = "<text>0</text>";
      } else {
        value = Number(value).toFixed(2);
      }
      _val = value.split('.');
      return html = _val[0] + '.' + _val[1];
    }
    var price1 = format(edata.price)
    if (edata.coupons) {
      var price2 = format(edata.price - edata.coupons[0].discount)
      var reduce = '券后立省' + edata.coupons[0].discount + '元'
    } else {
      var price2 = format(edata.price)
      var reduce = '券后立省' + 0 + '元'
    }
    function myCanvaspic(myCanvasId, imgbg, id) {
      console.log(id)
      console.log('star')
      const sharepic = wx.createCanvasContext(myCanvasId)
      console.log(imgbg)
      sharepic.drawImage(imgbg, 0, 0, 1080, 1920)
      sharepic.setFontSize(46)
      sharepic.setTextAlign('center')
      sharepic.setFillStyle('#404142')
      sharepic.fillText(str1, 540, 1013)
      sharepic.fillText(str2, 540, 1083)
      if (edata.tags.length > 0) {
        sharepic.rect(462, 1137, 164, 54)
        sharepic.setFillStyle('#ff4564')
        sharepic.fill()
        sharepic.setFontSize(35)
        sharepic.setTextAlign('center')
        sharepic.setFillStyle('white')
        sharepic.fillText(edata.tags, 544, 1178)
      }
      sharepic.setFontSize(60)
      sharepic.setTextAlign('center')
      sharepic.setFillStyle('#aaabad')
      sharepic.fillText(price1, 335, 1376)
      sharepic.setFillStyle('#ff4564')
      sharepic.fillText(price2, 750, 1376)
      sharepic.setFontSize(46)
      sharepic.fillText(reduce, 540, 1486)
      sharepic.drawImage(that.data.itempic, 297, 454, 486, 486)
      if (edata.is99) {
        sharepic.drawImage('/img/freeico.png', 760, 422, 243, 221)
      }
      sharepic.drawImage(that.data.dcode, 808, 1646, 236, 236)
      sharepic.draw(false, function (e) {
        console.log(e)
        wx.canvasToTempFilePath({
          x: 0,
          y: 0,
          width: 1080,
          height: 1920,
          destWidth: 1080,
          destHeight: 1920,
          canvasId: 'myCanvas',
          success: function (res) {
            console.log(res.tempFilePath)
            console.log(id)
            that.setData({
              shareimg1: res.tempFilePath
            });
          }
        })
        wx.canvasToTempFilePath({
          x: 0,
          y: 0,
          width: 1080,
          height: 1920,
          destWidth: 1080,
          destHeight: 1920,
          canvasId: 'myCanvas2',
          success: function (res) {
            console.log(res.tempFilePath)
            console.log(id)
            that.setData({
              shareimg2: res.tempFilePath
            });

          }
        })
        wx.canvasToTempFilePath({
          x: 0,
          y: 0,
          width: 1080,
          height: 1920,
          destWidth: 1080,
          destHeight: 1920,
          canvasId: 'myCanvas3',
          success: function (res) {
            console.log(res.tempFilePath)
            console.log(id)
            that.setData({
              sharepictc: true,
              shareimg3: res.tempFilePath,
              sharetc: false,
              over: true,
              saveimg: that.data.shareimg1,
              showmorepic: true
            });
            wx.hideLoading()
          }
        })
      })
    }
    myCanvaspic(myCanvasId1, imgbg1, 1)
    myCanvaspic(myCanvasId2, imgbg2, 2)
    myCanvaspic(myCanvasId3, imgbg3, 3)
  },
  shareweixinquan(){
    var that = this
    var edata = this.data.item
    wx.setStorage({
      key: "share",
      data: "true"
    })
    wx.showLoading({
      title: '生成中...',
      mask: true
    })
    console.log(this.data.item)
    var imgbgsrc
    if (edata.is99) {
      imgbgsrc = '/img/picbg3.jpg'
    } else {
      imgbgsrc = '/img/picbg.jpg'
    }
    console.log(imgbgsrc)
    function sharepic(data, link) {
      console.log(data)
      console.log(edata)
      if (data.data.code == 0) {
        var str = edata.title;
        str = str.slice(0, 30)
        var str1 = str.slice(0, 16)
        var str2 = str.slice(17, 30) + '...'
        var format = function (value) {
          var html, _val;
          value = Number(value).toFixed(2);
          if (value == 0) {
            value = 0;
            return html = "<text>0</text>";
          } else {
            value = Number(value).toFixed(2);
          }
          _val = value.split('.');
          return html = _val[0] + '.' + _val[1];
        }
        var price1 = format(edata.price)
        if (edata.coupons) {
          var price2 = format(edata.price - edata.coupons[0].discount)
          var reduce = '券后立省' + edata.coupons[0].discount + '元'
        } else {
          var price2 = format(edata.price)
          var reduce = '券后立省' + 0 + '元'
        }
        //本地化商品图片
        
        function myCanvaspic(myCanvasId, imgbg,id){
          console.log(id)
          console.log('star')
          const sharepic = wx.createCanvasContext(myCanvasId)
          console.log(imgbg)
          sharepic.drawImage(imgbg, 0, 0, 1080, 1920)
          sharepic.setFontSize(46)
          sharepic.setTextAlign('center')
          sharepic.setFillStyle('#404142')
          sharepic.fillText(str1, 540, 1013)
          sharepic.fillText(str2, 540, 1083)
          if (edata.tags.length > 0) {
            sharepic.rect(462, 1137, 164, 54)
            sharepic.setFillStyle('#ff4564')
            sharepic.fill()
            sharepic.setFontSize(35)
            sharepic.setTextAlign('center')
            sharepic.setFillStyle('white')
            sharepic.fillText(edata.tags, 544, 1178)
          }
          sharepic.setFontSize(60)
          sharepic.setTextAlign('center')
          sharepic.setFillStyle('#aaabad')
          sharepic.fillText(price1, 335, 1376)
          sharepic.setFillStyle('#ff4564')
          sharepic.fillText(price2, 750, 1376)
          sharepic.setFontSize(46)
          sharepic.fillText(reduce, 540, 1486)
          sharepic.drawImage(that.data.itempic, 297, 454, 486, 486)
          if (edata.is99) {
            sharepic.drawImage('/img/freeico.png', 760, 422, 243, 221)
          }
          sharepic.drawImage(that.data.dcode, 808, 1646, 236, 236)
          sharepic.draw(false,function (e) {
            console.log(e)
            wx.canvasToTempFilePath({
              x: 0,
              y: 0,
              width: 1080,
              height: 1920,
              destWidth: 1080,
              destHeight: 1920,
              canvasId: 'myCanvas',
              success: function (res) {
                console.log(res.tempFilePath)
                console.log(id)
                that.setData({
                  shareimg1: res.tempFilePath
                });
              }
            })
            wx.canvasToTempFilePath({
              x: 0,
              y: 0,
              width: 1080,
              height: 1920,
              destWidth: 1080,
              destHeight: 1920,
              canvasId: 'myCanvas2',
              success: function (res) {
                console.log(res.tempFilePath)
                console.log(id)
                that.setData({
                  shareimg2: res.tempFilePath
                });

              }
            })
            wx.canvasToTempFilePath({
              x: 0,
              y: 0,
              width: 1080,
              height: 1920,
              destWidth: 1080,
              destHeight: 1920,
              canvasId: 'myCanvas3',
              success: function (res) {
                console.log(res.tempFilePath)
                console.log(id)
                that.setData({
                  sharepictc: true,
                  shareimg3: res.tempFilePath,
                  sharetc: false,
                  over: true,
                  saveimg: that.data.shareimg1
                });
                wx.hideLoading()
              }
            })
          })
        }
      } else {
        wx.redirectTo({
          url: '/pages/index/index'
        })
      }
    }
    console.log(this.data.freeId)
    // if(this.data.freeId > 0){
    //   var scene = 'ui=' + getApp().globalData.userId + '&si=' + getApp().globalData.item.skuId + '&fr=' + this.data.freeId
    // }else{
      
    // }
    // var scene = 'ui=' + getApp().globalData.userId + '&si=' + getApp().globalData.item.skuId + '&f=t' + '&fr=' + this.data.freeId
    // console.log(scene)
    // const requestTask = wx.request({
    //   method: "POST",
    //   header: { "content-type": "application/x-www-form-urlencoded" },
    //   data: {
    //     scene: scene,
    //     page: 'pages/index/index',
    //     sessionId: app.globalData.sessionId,
    //     width: '236',
    //     auto_color: 'false',
    //     line_color: '{"r":"0","g":"0","b":"0"}',
    //     is_hyaline: 'false'
    //   },
    //   url: app.globalData.url + "/wxa/qrcode/getUnlimitQrcode",
    //   async: true,
    //   timeout: 10000,
    //   success: function (data) {
    //     console.log(data)
    //     console.log(data.data.qrcodeLink)
    //     sharepic(data, data.data.qrcodeLink)
    //   },
    //   error: function (textStatus) {
    //     console.error(textStatus);
    //   },
    //   complete: function (XMLHttpRequest, status) {
    //     if (status == 'timeout') {
    //       requestTask.abort()    // 超时后中断请求
    //       wx.showModal({
    //         title: '提示',
    //         content: '网络超时，请重试',
    //         showCancel: 'false',
    //         success: function (res) {
    //           if (res.confirm) {
    //             wx.redirectTo({
    //               url: '/pages/index/index'
    //             })
    //           }
    //         }
    //       })
    //     }
    //   }
    // })
  },
  saveimg(e) {
    var imgpath = ''
    console.log(e.currentTarget.dataset.id)
    if(e.currentTarget.dataset.id !== undefined){
      if(e.currentTarget.dataset.id == 1){
        imgpath = this.data.shareimg1
      }
      if(e.currentTarget.dataset.id == 2){
        imgpath = this.data.shareimg2
      }
      if(e.currentTarget.dataset.id == 3){
        imgpath = this.data.shareimg3
      }
    }else{
      imgpath = this.data.saveimg
    }
    var that = this
    wx.saveImageToPhotosAlbum({
      filePath: imgpath,
      success(res) {
        console.log('成功')
        wx.hideToast()
        app.globalData.newnotice = true
        that.setData({
          news: app.globalData.newnotice
        });
        console.log(that.data.news)
        wx.showModal({
          title: '提示',
          content: '分享图已经存到您的相册',
          success: function (res) {
            if (res.confirm) {
              console.log('用户点击确定')
              that.setData({
                sharepictc: false,
                shareimg: ''
              });
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })
      },
      fail(res){
        console.log(res)
      }
    })
  },
  back: function () {
    wx.navigateBack()
  },
})
